// 文章控制器
const db = require("../config/db");

// @desc    创建新文章
// @route   POST /api/posts
// @access  Private
const createPost = async (req, res) => {
  const { title, content, category_id } = req.body;
  const user_id = req.user.id; // 从 authMiddleware 获取

  if (!title || !content) {
    return res.status(400).json({ message: "标题和内容为必填项" });
  }

  try {
    const [result] = await db.query(
      "INSERT INTO posts (title, content, user_id, category_id) VALUES (?, ?, ?, ?)",
      [title, content, user_id, category_id || null]
    );
    const [newPost] = await db.query("SELECT * FROM posts WHERE id = ?", [
      result.insertId,
    ]);
    res.status(201).json(newPost[0]);
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: "服务器错误" });
  }
};

// @desc    获取所有文章（分页）
// @route   GET /api/posts
// @access  Public
const getAllPosts = async (req, res) => {
  const page = parseInt(req.query.page, 10) || 1;
  const limit = parseInt(req.query.limit, 10) || 10;
  const offset = (page - 1) * limit;
  const categoryId = req.query.category_id;
  const search = req.query.search;

  // --- 使用独立的数组来管理 WHERE 条件的参数，更清晰 ---
  let whereConditions = [];
  let whereValues = [];

  if (categoryId) {
    whereConditions.push("p.category_id = ?");
    whereValues.push(categoryId);
  }

  if (search) {
    // --- 使其同时搜索 title 和 category name ---
    whereConditions.push("(p.title LIKE ? OR c.name LIKE ?)");
    // --- 为两个占位符提供参数 ---
    const searchTerm = `%${search}%`;
    whereValues.push(searchTerm);
    whereValues.push(searchTerm);
  }

  const whereClause =
    whereConditions.length > 0 ? `WHERE ${whereConditions.join(" AND ")}` : "";

  try {
    // 构建用于计数的查询
    const countQuery = `SELECT COUNT(*) as total 
                        FROM posts p 
                        LEFT JOIN categories c ON p.category_id = c.id
                        ${whereClause}`;
    // 注意：计数查询也需要 JOIN categories 表，因为它现在是 WHERE 条件的一部分
    const [[{ total }]] = await db.query(countQuery, whereValues);

    // 构建用于获取数据的查询
    const postsQuery = `SELECT 
                          p.id, p.title, LEFT(p.content, 120) as content_summary, p.created_at, p.updated_at,
                          u.id as user_id, u.username as author,
                          c.id as category_id, c.name as categoryName
                        FROM posts p
                        JOIN users u ON p.user_id = u.id
                        LEFT JOIN categories c ON p.category_id = c.id
                        ${whereClause}
                        ORDER BY p.created_at DESC
                        LIMIT ? OFFSET ?`;

    // --- 组合所有参数 ---
    const finalValues = [...whereValues, limit, offset];
    const [posts] = await db.query(postsQuery, finalValues);

    res.json({
      data: posts,
      meta: {
        totalItems: total,
        totalPages: Math.ceil(total / limit),
        currentPage: page,
        itemsPerPage: limit,
      },
    });
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: "Server error" });
  }
};

// @desc    获取单篇文章
// @route   GET /api/posts/:id
// @access  Public
const getPostById = async (req, res) => {
  const { id } = req.params;
  try {
    const [posts] = await db.query(
      `SELECT 
         p.id, p.title, p.content, p.created_at, p.updated_at,
         u.id as user_id, u.username as author,
         c.id as category_id, c.name as categoryName
       FROM posts p
       JOIN users u ON p.user_id = u.id
       LEFT JOIN categories c ON p.category_id = c.id
       WHERE p.id = ?`,
      [id]
    );

    if (posts.length === 0) {
      return res.status(404).json({ message: "文章未找到" });
    }
    res.json(posts[0]);
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: "服务器错误" });
  }
};

// @desc    更新文章
// @route   PUT /api/posts/:id
// @access  Private
const updatePost = async (req, res) => {
  const { id } = req.params;
  const { title, content, category_id } = req.body;
  const user_id = req.user.id;

  try {
    // 检查文章是否存在且属于当前用户
    const [posts] = await db.query("SELECT user_id FROM posts WHERE id = ?", [
      id,
    ]);
    if (posts.length === 0) {
      return res.status(404).json({ message: "文章未找到" });
    }
    if (posts[0].user_id !== user_id) {
      return res.status(403).json({ message: "用户无权更新此文章" });
    }

    // 执行更新
    await db.query(
      "UPDATE posts SET title = ?, content = ?, category_id = ? WHERE id = ?",
      [title, content, category_id || null, id]
    );

    const [updatedPost] = await db.query("SELECT * FROM posts WHERE id = ?", [
      id,
    ]);
    res.json(updatedPost[0]);
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: "服务器错误" });
  }
};

// @desc    删除文章
// @route   DELETE /api/posts/:id
// @access  Private
const deletePost = async (req, res) => {
  const { id } = req.params;
  const user_id = req.user.id;

  try {
    // 检查文章是否存在且属于当前用户
    const [posts] = await db.query("SELECT user_id FROM posts WHERE id = ?", [
      id,
    ]);
    if (posts.length === 0) {
      return res.status(404).json({ message: "文章未找到" });
    }
    if (posts[0].user_id !== user_id) {
      return res.status(403).json({ message: "用户无权删除此文章" });
    }

    // 执行删除
    await db.query("DELETE FROM posts WHERE id = ?", [id]);
    res.status(204).send();
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: "服务器错误" });
  }
};

module.exports = {
  createPost,
  getAllPosts,
  getPostById,
  updatePost,
  deletePost,
};
